const { baseUrl } = require('./baseUrl.js');
var showModal = false
wx.onAppHide(() => {
  showModal = false
})
wx.onNetworkStatusChange(({isConnected, networkType}) => {
  if (!isConnected) {
    wx.showToast({
      title: '当前网络不稳定',
      icon: 'none',
      duration: 2000
    })
  }
})

//基本参数配置
const config = {
  // baseUrl: 'https://cpic-test.zhilingsd.com/api'
  baseUrl: `https://${baseUrl}/api`
  // baseUrl: 'https://cpic-dev.zhilingsd.com/api'
  // baseUrl: 'http://192.168.7.78:8004'
}

// 时间处理器
const timestampToTime = function (time) {
  // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  if (time) {
    var date = new Date(time)
    var Y = date.getFullYear() + '-'
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
    return Y + M + D + h + m + s
  }
}

if(!Promise.prototype.finally){
  Promise.prototype.finally = function(callback){
      return this.then(res=>{
          callback&&callback(res)
      },error=>{
          callback&&callback(error)
      })
  }
}

//网络请求
let request = function(options) {
  const Param = {
    method: options.url,
    app_key: null,
    session: wx.getStorageSync("token"),
    v: '1.0',
    partner_id: null,
    timestamp: timestampToTime(new Date()),
    data: options.data
  }
  return new Promise((resolve,reject) => {
    wx.request({
      url: config.baseUrl + '/route/rest',
      method: options.method || 'POST',
      data: Param,
      header: options.header || { 
        accept: 'application/json'
      },
      complete: () => {
        let complete = options.complete
        if ('function' === typeof complete) {
          complete()
        }
      },
      success: res => {
        const name = options.url + '_response'
        for (var key in res.data) {
          if (key === name) {
            resolve(res.data[key])
          }
          if (key === 'error_response') {
            if (res.data[key].sub_code === 'login_timout' || res.data[key].sub_code === 'check_token_failed') {
              console.log('2', wx.getStorageSync("isLogin"))
              if (!showModal && !wx.getStorageSync("isLogin")) {
                wx.redirectTo({
                  url: '/pages/login/wechat/wechat',
                })
              } else {
                if (!showModal || wx.getStorageSync("isLogin")) {
                  showModal = true
                  wx.setStorageSync("isLogin", false)
                  wx.showModal({
                    content: res.data[key].sub_msg,
                    showCancel: false,
                    success () {
                      wx.redirectTo({
                        url: '/pages/login/wechat/wechat',
                      })
                      showModal = false
                    }
                  })
                }
              }
            } else {
              if (!showModal) {
                showModal = true
                wx.showModal({
                  content: res.data[key].sub_msg,
                  showCancel: false,
                  success (res) {
                    if (res.confirm) {
                    showModal = false
                    }
                  }
                })
              }
            }
            reject(res)
          }
        }
      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常，请重试',
          icon: 'none',
          duration: 2000
        })
        
        reject(e)
      },
    })
  })
}
const post = function(options) {
  options.method = 'POST'
  return request(options)
}
const get = function(options) {
  options.method = 'GET'
  return request(options)
}
let login = function(options) {
  return new Promise((resolve,reject) => {
    wx.request({
      url: config.baseUrl + (options.url || ''),
      method: options.method || 'POST',
      data: options.data || {},
      header: options.header || {
        accept: 'application/json'
      },
      complete: () => {
        let complete = options.complete
        if ('function' === typeof complete) {
          complete()
        }
      },
      success: res => {
        let { code } = res.data
        let success = options.success
        if (code === 200000) {
          resolve(res.data)
        } else {
          if (!showModal) {
            showModal = true
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success (res) {
              if (res.confirm) {
              showModal = false
              }
            }
          })
        }
          reject(res.data)
        }
      },
      fail: function(e) {
        if (!showModal) {
          showModal = true
        wx.showModal({
          content: '网络异常，请重试',
          showCancel: false,
          success (res) {
            if (res.confirm) {
            showModal = false
            }
          }
        })
      }
        reject(e)
      },
    })
  })
}
let getArrayBuffer = function(options) {
  return new Promise((resolve,reject) => {
    wx.request({
      url: config.baseUrl + (options.url || ''),
      method: options.method || 'POST',
      data: options.data || {},
      header: options.header || {
        accept: 'application/json'
      },
      responseType: 'arraybuffer',
      complete: () => {
        let complete = options.complete
        if ('function' === typeof complete) {
          complete()
        }
      },
      success: res => {
        resolve(res.data)
      },
      fail: function(e) {
        if (!showModal) {
          showModal = true
        wx.showModal({
          content: '网络异常，请重试',
          showCancel: false,
          success (res) {
            if (res.confirm) {
            showModal = false
            }
          }
        })
      }
        reject(e)
      },
    })
  })
}
let chooseImageUpload = function(number, needCut = false) {
  return new Promise((resolve, reject) => {
    let that = this
    wx.chooseImage({
      count: number && number || 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success (res) {
        console.log('选择系统返回', res)
        let file = res.tempFiles[0]
        let callback = () => {
          let formData = {
            method: 'upload_multipart_file',
            app_key: null,
            session: wx.getStorageSync("token"),
            v: '1.0',
            partner_id: null,
            timestamp: timestampToTime(new Date()),
          }
          wx.uploadFile({
            url: config.baseUrl + '/cpic/UploadImg',
            filePath: file.path,
            name: 'file',
            header: {
              accept: 'application/json'
            },
            formData,
            success(res) {
              console.log('上传成功后返回', res)
              let data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
              console.log('转换后后返回', data)
              resolve(data)
            },
            fail(err) {
              console.log(err)
              reject(err)
            }
          })
        }
        if(needCut) {
          resolve(file)
        } else {
          callback(file)
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
// 选择多张一张一张上传
let uploadImg = function () {
  wx.chooseImage({
    count: 5,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: function (res) {
    var successUp = 0 //成功
    var failUp = 0 //失败
    var length = res.tempFilePaths.length //总数
    var count = 0 //第几张
    uploadOneByOne(res.tempFilePaths,successUp,failUp,count,length)
   }
  })
 }
 let uploadOneByOne = function (imgPaths,successUp, failUp, count, length) {
  wx.showLoading({
  title: '正在上传第'+count+'张'
  })
  let formData = {
    method: 'upload_multipart_file',
    app_key: null,
    session: wx.getStorageSync("token"),
    v: '1.0',
    partner_id: null,
    timestamp: timestampToTime(new Date()),
  }
  wx.uploadFile({
  url: config.baseUrl + '/cpic/UploadImg',
  filePath: imgPaths[count],
  name: 'file',
  header: {
    accept: 'application/json'
  },
  formData,
  success:function(res){
    successUp++;//成功+1
    console.log('上传成功后返回', res)
    let data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
    console.log('转换后后返回', data)
  },
  fail:function(e){
    failUp++;//失败+1
  },
  complete:function(e){
    count++;//下一张
    if(count == length){
    //上传完毕，作一下提示
    console.log('上传成功' + successUp + ',' + '失败' + failUp);
    wx.showToast({
    title: '上传成功' + successUp,
    icon: 'success',
    duration: 2000
    })
    } else {
      //递归调用，上传下一张
      uploadOneByOne(imgPaths, successUp, failUp, count, length);
      console.log('正在上传第' + count + '张');
      }
    }
  })
  }
  // 获取手机号码接口
  let getPhoneNumber = function(options) {
    return new Promise((resolve,reject) => {
      wx.request({
        url: config.baseUrl + (options.url || ''),
        method: options.method || 'POST',
        data: options.data || {},
        header: options.header || {
          accept: 'application/json'
        },
        complete: () => {
          let complete = options.complete
          if ('function' === typeof complete) {
            complete()
          }
        },
        success: res => {
          let { code } = res.data
          let success = options.success
          if (code === 200000) {
            resolve(res.data)
          } else {
            if (!showModal) {
              showModal = true
            wx.showModal({
              content: res.data.msg,
              showCancel: false,
              success (res) {
                if (res.confirm) {
                showModal = false
                }
              }
            })
          }
            reject(res.data)
          }
        },
        fail: function(e) {
          if (!showModal) {
            showModal = true
          wx.showModal({
            content: '网络异常，请重试',
            showCancel: false,
            success (res) {
              if (res.confirm) {
              showModal = false
              }
            }
          })
        }
          reject(e)
        },
      })
    })
  }
  // 获取商户列表接口
  let getMerchantList = function(options) {
    return new Promise((resolve,reject) => {
      wx.request({
        url: config.baseUrl + (options.url || ''),
        method: options.method || 'POST',
        data: options.data || {},
        header: options.header || {
          accept: 'application/json'
        },
        complete: () => {
          let complete = options.complete
          if ('function' === typeof complete) {
            complete()
          }
        },
        success: res => {
          let { code } = res.data
          let success = options.success
          if (code === 200000) {
            resolve(res.data)
          } else {
            if (!showModal) {
              showModal = true
            wx.showModal({
              content: res.data.msg,
              showCancel: false,
              success (res) {
                if (res.confirm) {
                showModal = false
                }
              }
            })
          }
            reject(res.data)
          }
        },
        fail: function(e) {
          if (!showModal) {
            showModal = true
          wx.showModal({
            content: '网络异常，请重试',
            showCancel: false,
            success (res) {
              if (res.confirm) {
              showModal = false
              }
            }
          })
        }
          reject(e)
        },
      })
    })
  }

module.exports = {
  request,
  post,
  get,
  login,
  getArrayBuffer,
  chooseImageUpload,
  uploadImg,
  config,
  getPhoneNumber,
  getMerchantList
}
